<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>懒加载</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        li {
            list-style: none;
            height: 600px;
            box-sizing: border-box;
            border: 1px solid black;
        }

        img {
            display: block;
            margin: 100px auto;
        }
    </style>
</head>

<body>
    <div id="box">
        <ul>
            <li>
                <img data-src="./图片懒加载/1.jpg" src="./图片懒加载/default.jpg" alt="">
            </li>
            <li>
                <img data-src="./图片懒加载/2.jpg" src="./图片懒加载/default.jpg" alt="">
            </li>
            <li>
                <img data-src="./图片懒加载/3.jpg" src="./图片懒加载/default.jpg" alt="">
            </li>
            <li>
                <img data-src="./图片懒加载/4.jpg" src="./图片懒加载/default.jpg" alt="">
            </li>
            <li>
                <img data-src="./图片懒加载/5.jpg" src="./图片懒加载/default.jpg" alt="">
            </li>
            <li>
                <img data-src="./图片懒加载/6.jpg" src="./图片懒加载/default.jpg" alt="">
            </li>
            <li>
                <img data-src="./图片懒加载/7.jpg" src="./图片懒加载/default.jpg" alt="">
            </li>
            <li>
                <img data-src="./图片懒加载/8.jpg" src="./图片懒加载/default.jpg" alt="">
            </li>
            <li>
                <img data-src="./图片懒加载/9.jpg" src="./图片懒加载/default.jpg" alt="">
            </li>
            <li>
                <img data-src="./图片懒加载/10.jpg" src='./图片懒加载/10.jpg'>
            </li>
        </ul>
    </div>
    <script>
        function imgonload() {
            let img = document.querySelectorAll("img");
            /*console.log(img);*/
            for (let i = 0; i < img.length; i++) {
                if (img[i].getBoundingClientRect().top < window.innerHeight) {
                    //图片一旦有src就会加载出来，所以图片的路径不会放在src中，而是一个自定义的属性data-src中
                    img[i].src = img[i].dataset.src;
                }
            }
        }

        function scollImg(fn) {
            let timer = null;
            let context = this;
            return function () {
                clearTimeout(timer);
                timer = setTimeout(() => {
                    fn.apply(context);
                }, 500)
            }
        }
        window.onload = imgonload;
        window.onscroll = scollImg(imgonload);
    </script>
</body>

</html>